package com.cxb.springboot.filter;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @Classname WebVisitFilter
 * @Date 2023/4/14 23:30
 * @Created by Administrator
 * @Description TODO
 */
@WebFilter(filterName = "logFilter", urlPatterns = {"/upload/file"})
@Slf4j
public class WebVisitFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    /**
     * 输出访问 ip
     */
    /*@Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        //获取访问 ip 地址
        HttpServletRequest req = (HttpServletRequest) request;
        String visitIp = req.getRemoteAddr();
        visitIp = "0:0:0:0:0:0:0:1".equals(visitIp) ? "127.0.0.1" : visitIp;
        // 每次拦截到请求输出访问 ip
        System.out.println("访问 IP = " + visitIp);
        String paramsFromRequestBody = getParamsFromRequestBody(req);
        System.out.println("参数：" + paramsFromRequestBody);
        chain.doFilter(req, response);
    }*/

    /**
     * 对 request 进行包装
     *
     * @param request
     * @param response
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        MyHttpServletRequestWrapper requestWrapper = new MyHttpServletRequestWrapper((HttpServletRequest) request);
        chain.doFilter(requestWrapper, response);
    }

    @Override
    public void destroy() {

    }

    /* *
     * 获取请求体内容
     * @return
     * @throws IOException
     */
    private String getParamsFromRequestBody(HttpServletRequest request) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] bytes = new byte[1024];
        int i;
        ServletInputStream inputStream = request.getInputStream();
        try {
            //将输入流中的数据读到bytes中，i表示bytes的长度，当读完时i=-1退出循环
            while ((i = inputStream.read(bytes)) != -1) {
                //将指定的字节数组从偏移量off开始，写入i个字节到输出流
                bos.write(bytes, 0, i);
            }
        } catch (Exception e) {
            log.error("输入流转字节数组失败", e);
        } finally {
            inputStream.close();
        }
        return new String(bos.toByteArray());
    }

}
